/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action.retail;

import static com.opensymphony.xwork2.Action.ERROR;
import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import database.AuthenticationDAO;
import java.util.Map;
import model.Customer;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;

/**
 *
 * @author Thai Ha Cong
 */
@Namespace("/Member")
public class MemberProfileAction extends ActionSupport implements ModelDriven<Customer> {

    private Customer customer = new Customer();
    private AuthenticationDAO adao = new AuthenticationDAO();

    public MemberProfileAction() {
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    @Action(value = "editProfileForm", results = {
        @Result(name = "success", location = "/member/editProfile.jsp"),
        @Result(name = "input", location = "/member/editProfile.jsp")
    })
    @SkipValidation
    public String editProfileForm() {
        Map session = ActionContext.getContext().getSession();
        
        customer = (Customer) session.get("currentCustomer");

        return SUCCESS;
    }

    @Action(value = "editProfile", results = {
        @Result(name = "success", location = "/member/customerProfile.jsp"),
        @Result(name = "input", location = "/member/editProfile.jsp")
    })
    public String editProfile() {
        Map session = ActionContext.getContext().getSession();
        Customer oldCustomer = (Customer) session.get("currentCustomer");
        customer.setIdCustomer(oldCustomer.getIdCustomer());
        
        if (adao.updateProfile(customer)) {
            addActionMessage("Your Profile has been changed successfully.");
            
            customer = adao.getCustomerFromUsername(oldCustomer.getMemeberaccount().getUsername());
            session.put("currentCustomer", customer);
            return SUCCESS;
        } else {
            addActionError("Cannot Update Profile. Please try again later.");
            return INPUT;
        }
    }

    @Override
    @VisitorFieldValidator(message = "", appendPrefix = false)
    public Customer getModel() {
        return customer;
    }
}